﻿using Microsoft.AspNetCore.Mvc.ModelBinding;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;

namespace web_api.Helpers {
  public class ArrayModelBinder : IModelBinder {
    public Task BindModelAsync(ModelBindingContext bindingContext) {
      if (!bindingContext.ModelMetadata.IsEnumerableType) {
        bindingContext.Result = ModelBindingResult.Failed();
        return Task.CompletedTask;
      }
      var value = bindingContext.ValueProvider.GetValue(bindingContext.ModelName).ToString();
      if (string.IsNullOrWhiteSpace(value)) {
        bindingContext.Result = ModelBindingResult.Success(null);
      }
      var elementTye = bindingContext.ModelType.GetTypeInfo().GenericTypeArguments[0];
      var converter = TypeDescriptor.GetConverter(elementTye);
      var values = value.Split(new[] { "," }, StringSplitOptions.RemoveEmptyEntries).Select(x => converter.ConvertFromString(x.Trim())).ToArray();
      var typedValus = Array.CreateInstance(elementTye, values.Length);
      values.CopyTo(typedValus, 0);
      bindingContext.Model = typedValus;
      bindingContext.Result = ModelBindingResult.Success(bindingContext.Model);
      return Task.CompletedTask;
    }
  }
}
